<?php

namespace app\common\model\apply;

use app\admin\model\ProjectFeeitem;
use app\common\library\Utils;
use app\common\model\User;
use think\facade\Db;
use think\facade\Log;
use think\Model;

/**
 * Reimbursement
 */
class Reimbursement extends Model
{
    // 表名
    protected $name = 'apply_reimbursement';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function getAmountAttr($value): float
    {
        return (float)$value;
    }

    public function project(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\common\model\Project::class, 'project_id', 'id');
    }

    public function feeitem(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Feeitem::class, 'feeitem_id', 'id');
    }

    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function getImageAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setImageAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getFilesAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setFilesAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public static function onBeforeInsert(Model $model): void
    {
        $model->no = Utils::createNo('BX');
    }

    public static function onAfterWrite(Model $model): void
    {
        if(isset($model->paid) && $model->paid == 1){
            $modelData = $model->find($model->id);
            $feeitems = $modelData->feeitems;
            if(!is_array($modelData->feeitems)){
                $feeitems = json_decode($feeitems, true);
            }
            foreach ($feeitems as $v) {
                $sql = 'update ba_project_feeitem set paid = paid + '.$v['amount'].' where project_id = '.$modelData->project_id.' and feeitem_id = '.$v['feeitem_id'];
                Db::query($sql);
            }
        }
    }
}